using System.Data;
using System.Text.Json;

namespace 后端服务.Models;

/// <summary>
/// SQL查询结果模型，用于处理动态结果集
/// </summary>
public class SqlQueryResult
{
    /// <summary>
    /// 列名列表
    /// </summary>
    public List<string> Columns { get; set; } = new();
    
    /// <summary>
    /// 数据行列表
    /// </summary>
    public List<Dictionary<string, object?>> Rows { get; set; } = new();
    
    /// <summary>
    /// 从DataReader构建结果集
    /// </summary>
    /// <param name="reader">数据读取器</param>
    /// <returns>查询结果</returns>
    public static async Task<SqlQueryResult> FromDataReaderAsync(IDataReader reader)
    {
        var result = new SqlQueryResult();
        
        // 获取列名
        for (int i = 0; i < reader.FieldCount; i++)
        {
            result.Columns.Add(reader.GetName(i));
        }
        
        // 读取数据
        while (await Task.Run(() => reader.Read()))
        {
            var row = new Dictionary<string, object?>();
            for (int i = 0; i < reader.FieldCount; i++)
            {
                var columnName = reader.GetName(i);
                row[columnName] = reader[i] == DBNull.Value ? null : reader[i];
            }
            result.Rows.Add(row);
        }
        
        return result;
    }
    
    /// <summary>
    /// 转换为JSON字符串
    /// </summary>
    /// <returns>JSON格式的查询结果</returns>
    public string ToJson()
    {
        return JsonSerializer.Serialize(this, new JsonSerializerOptions
        {
            WriteIndented = true
        });
    }
}